const app = getApp();

Page({
  data: {
    categories: [],
    products: [],
    currentCategory: null
  },

  onLoad() {
    this.loadCategories();
  },

  async loadCategories() {
    try {
      const res = await app.request({
        url: '/product/categories/',
        method: 'GET'
      });
      
      this.setData({
        categories: res.data,
        currentCategory: res.data[0]?.id
      });
      
      if (this.data.currentCategory) {
        this.loadProducts(this.data.currentCategory);
      }
    } catch (error) {
      wx.showToast({
        title: '加载分类失败',
        icon: 'none'
      });
    }
  },

  async loadProducts(categoryId) {
    try {
      const res = await app.request({
        url: '/product/products/',
        method: 'GET',
        data: {
          category: categoryId
        }
      });
      
      this.setData({
        products: res.data
      });
    } catch (error) {
      wx.showToast({
        title: '加载商品失败',
        icon: 'none'
      });
    }
  },

  handleCategoryChange(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      currentCategory: categoryId
    });
    this.loadProducts(categoryId);
  }
}); 